package Java.FockJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

//分支合并框架

class MyTak extends RecursiveTask<Integer> {

    //拆分差值不能超过十,计算10以内的运算
    private static final Integer value = 10;
    private int begin;  //拆分开始值
    private int end; //拆分结束值
    private int result;  //返回结果

    //创建有参数的构造
    public MyTak(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }


    //拆分和合并过程
    @Override
    protected Integer compute() {

        //判断是否相加的两个数值是否大于10
        if ((end - begin) <= value) {
            //相加操作
            for (int i = begin; i <= end; i++) {
                result = result + i;
            }

        } else {
            //进一步拆分
            int middle = (begin + end) / 2;
            //拆分左边
            MyTak task01 = new MyTak(begin, middle);

            //拆分右边
            MyTak task02 = new MyTak(middle + 1, end);
            //调用方法拆分
            task01.fork();
            task02.fork();

            //合并结果
            result = task01.join() + task02.join();
        }
        return result;
    }
}

public class FockJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建拆分任务对象
        MyTak myTak = new MyTak(0, 100);
        //创建分支合并池对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTak);
        //获取合并之后的结果
        Integer result = forkJoinTask.get();
        System.out.println(result);
        //关闭池对象
        forkJoinPool.shutdown();


    }
}
